<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="accountSelected" placeholder="请选择公众号" clearable class="filter-item" style="width: 200px;margin-right: 20px">
        <el-option v-for="item in accountListOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-refresh" @click="syncAccountFans">
        同步粉丝
      </el-button>
    </div>
    <div class="filter-container">
      <el-select v-model="listQuery.wxAccountId" placeholder="请选择公众号" clearable class="filter-item" style="width: 200px;margin-right: 20px">
        <el-option v-for="item in accountListOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-input
        v-model="listQuery.nicknameStr"
        :placeholder="'请输入' + tempDesc.nicknameStr"
        style="width: 200px;margin-right: 20px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-refresh" @click="handleFilter">
        刷新
      </el-button>
      <!--<el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"-->
      <!--@click="handleCreate">{{ $t('table.add') }}-->
      <!--</el-button>-->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column :label="tempDesc.wxAccountName">
        <template slot-scope="scope">
          <span>{{ scope.row.wxAccountName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.nicknameStr" width="200px">
        <template slot-scope="scope">
          <span>
            {{ scope.row.nicknameStr }}
          </span>
          <br>
          <el-tag v-for="(item, index) in scope.row.tagList" :key="index" type="small" style="margin-top: 5px;margin-right: 5px;" hit>
            {{ item.name }}
          </el-tag>
          <el-row type="flex" class="row-bg" justify="center">
            <el-col :span="6">
              <div class="grid-content bg-purple" />
            </el-col>
            <el-col :span="6">
              <div class="grid-content bg-purple-light" />
            </el-col>
            <el-col :span="6">
              <div class="grid-content bg-purple" />
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.headimgUrl" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-popover
            placement="top-start"
            trigger="hover"
          >
            <span>
              <img :src="scope.row.headimgUrl" alt="" style="width: 200px;height: 200px">
            </span>
            <span slot="reference">
              <img :src="scope.row.headimgUrl" alt="" style="width: 50px;height: 50px">
            </span>
          </el-popover>
        </template>
      </el-table-column>
      <!--<el-table-column label="标签">-->
      <!--<template slot-scope="scope">-->

      <!--<el-tag v-for="(item, index) in scope.row.tagList" :key="index">-->
      <!--{{item.name}}-->
      <!--</el-tag>-->

      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column :label="tempDesc.gender" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.gender ==0 ? '未知': (scope.row.gender==1 ? '男':'女') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.language" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.language }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.country" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.country }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.province" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.province }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.city" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.city }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column :label="tempDesc.openid" show-overflow-tooltip>-->
      <!--<template slot-scope="scope">-->
      <!--<span>{{ scope.row.openid }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column :label="tempDesc.subscribeStatus" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-tag :type="scope.row.subscribeStatus == 1 ? 'success' : 'danger'" hit>
            {{ scope.row.subscribeStatus == 1 ? '已订阅' : '未订阅' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.subscribeTime" width="160px" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.subscribeTime }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column :label="tempDesc.remark" width="120px">-->
      <!--<template slot-scope="scope">-->
      <!--<span>{{ scope.row.remark }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <!--<el-table-column :label="tempDesc.wxAccountAppid" width="150px" show-overflow-tooltip>-->
      <!--<template slot-scope="scope">-->
      <!--<span>{{ scope.row.wxAccountAppid }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <!--<el-table-column :label="tempDesc.createTime" width="160px" show-overflow-tooltip>-->
        <!--<template slot-scope="scope">-->
          <!--<span>{{ scope.row.createTime }}</span>-->
        <!--</template>-->
      <!--</el-table-column>-->
      <!--<el-table-column :label="tempDesc.updateTime" width="160px" show-overflow-tooltip>-->
        <!--<template slot-scope="scope">-->
          <!--<span>{{ scope.row.updateTime }}</span>-->
        <!--</template>-->
      <!--</el-table-column>-->

      <el-table-column v-if="checkBtnPermission(['accountFansList:delete','accountFansList:quickres'])" :label="$t('table.actions')" width="200px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-has="'accountFansList:delete'" type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">
            {{ $t('table.delete') }}
          </el-button>
          <el-button v-has="'accountFansList:quickres'" type="primary" size="mini" style="width: 80px;margin-left: 10px" @click="handleUpdate(scope.row)">
            快捷回复
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog title="快捷回复" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="tempFansMsg"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="消息类型" prop="msgType">
          <el-select v-model="tempFansMsg.msgType" class="filter-item" placeholder="请选择消息类型" style="width: 280px;" @change="onMsgTypeChange">
            <el-option v-for="item in fansMsgOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item v-show="tempFansMsg.msgType == 'text'" label="内容" prop="content">
          <el-input v-model="tempFansMsg.content" type="textarea" :rows="7" maxlength="100" placeholder="请输入消息内容" />
        </el-form-item>
        <el-form-item v-show="tempFansMsg.msgType == 'mpnews'" label="提示">
          <span style="font-weight: bold;font-size:14px;">仅能发送单图文</span>
        </el-form-item>

        <el-form-item v-show="tempFansMsg.msgType == 'mpnews'" label="模板名称" prop="tplId">
          <el-select v-model="tempFansMsg.tplId" class="filter-item" placeholder="请选择模板" style="width: 280px;" clearable>
            <el-option v-for="item in newsTplOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { checkBtnPermission } from '@/utils/permission' // 权限判断函数
import { fetchList, createRow, updateRow, deleteRow, syncAccountFans, sendMsg } from '@/api/wx-account-fans'
import { fetchAllAccount } from '@/api/wx-account'
import { fetchAllNewsTpl2 } from '@/api/wx-news-template'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

// 常量title
const tempDesc = {
  'id': '',
  'openid': 'openID',
  'subscribeStatus': '订阅状态',
  'subscribeTime': '订阅时间',
  'gender': '性别',
  'language': '语言',
  'country': '国家',
  'province': '省份',
  'city': '城市',
  'headimgUrl': '头像',
  'remark': '备注',
  'wxAccountAppid': '公众号appID',
  'createTime': '创建时间',
  'updateTime': '更新时间',
  'nickname': '昵称',
  'nicknameStr': '昵称',
  'wxAccountName': '公众号名称'
}

const fansMsgOptions = [
  { key: 'text', display_name: '文本消息' },
  { key: 'mpnews', display_name: '图文消息' }
]

export default {
  // name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        nicknameStr: '',
        wxAccountId: ''
      },
      showReviewer: false,
      temp: {
        'id': '',
        'openid': '',
        'subscribeStatus': '',
        'subscribeTime': '',
        'gender': '',
        'language': '',
        'country': '',
        'province': '',
        'city': '',
        'headimgUrl': '',
        'remark': '',
        'wxAccountAppid': '',
        'createTime': '',
        'updateTime': '',
        'nickname': '',
        'nicknameStr': '',
        'wxAccountName': ''
      },
      tempDesc: tempDesc,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '增加'
      },
      rules: {
        msgType: [{ required: true, message: '请选择消息类型', trigger: 'blur' }]
        // content: [{required: true, message: '请输入内容', trigger: 'blur'}],
        // tplId: [{required: true, message: '请选择模板', trigger: 'blur'}]
      },
      accountListOptions: [

      ],
      accountSelected: '',
      tempFansMsg: {
        fansId: '',
        msgType: '',
        content: '',
        tplId: ''
      },
      fansMsgOptions,
      newsTplOptions: []
    }
  },
  created() {
    this.getList()
    this.getAccountList()
  },
  methods: {
    checkBtnPermission,
    getList() {
      this.listLoading = true
      this.getAccountList()
      fetchList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        'id': '',
        'name': '',
        'account': '',
        'appid': '',
        'appsecret': '',
        'url': '',
        'token': '',
        'aeskey': ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createRow(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true

      this.getAllNewsTpl()

      this.$nextTick(() => {
        this.tempFansMsg.content = ''
        this.tempFansMsg.tplId = ''
        this.tempFansMsg.fansId = ''
        this.tempFansMsg.msgType = 'text'// 默认文本消息
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      if (this.tempFansMsg.msgType == 'text' && !this.tempFansMsg.content) {
        this.$message({ message: '请输入内容', type: 'warning' })
        return false
      }
      if (this.tempFansMsg.msgType == 'mpnews' && !this.tempFansMsg.tplId) {
        this.$message({ message: '请选择模板', type: 'warning' })
        return false
      }

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.tempFansMsg)
          tempData.fansId = this.temp.id
          sendMsg(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '发送成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = { 'id': row.id }
        deleteRow(params).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      })
    },
    getAccountList() {
      fetchAllAccount().then(response => {
        this.accountListOptions = []
        for (var i = 0; i < response.data.length; i++) {
          this.accountListOptions.push({ 'key': response.data[i].id + '', 'display_name': response.data[i].name })
        }
      })
    },
    syncAccountFans() {
      if (this.accountSelected == '') {
        this.$message({ message: '请选择公众号', type: 'warning' })
        return false
      }
      this.$confirm('确认需要同步粉丝信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = { 'id': this.accountSelected }
        syncAccountFans(params).then(response => {
          this.getList()
          this.$notify({
            title: '成功',
            message: '同步粉丝成功，请稍后刷新数据查看',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    getAllNewsTpl() {
      const _this = this
      var params = { 'wxAccountId': _this.temp.wxAccountId }
      fetchAllNewsTpl2(params).then(response => {
        var _newsTplOptions = []
        for (var i = 0; i < response.data.length; i++) {
          _newsTplOptions.push({ 'key': response.data[i].id + '', 'display_name': response.data[i].tplName })
        }
        _this.newsTplOptions = _newsTplOptions
      })
    },
    onMsgTypeChange(value) {
      if (value === '') {
        this.tempFansMsg.tplId = ''
        this.tempFansMsg.content = ''
      }
      if (value === 'text') {
        this.tempFansMsg.tplId = ''
      }
      if (value === 'mpnews') {
        this.tempFansMsg.content = ''
      }
    }
  }
}
</script>
